﻿using System;
using System.Buffers;
using System.Text;
using Microsoft.Extensions.Logging;
using Serilog;
using SuperSocket.ProtoBase;

namespace Lawn.AppServer
{
    public class MessagePipelineFilter:FixedHeaderPipelineFilter<MessagePackageInfo>
    {


        
        // 25 00[type]+total_len（2字节）+topiclen（2字节）+topic+[content len2字节]+[content]+[23 24].
        //01登录 02 请求响应 03请求发送，04 订阅，04退出，
        public MessagePipelineFilter() : base(4)
        {
           
        }

        
        
        
        protected override int GetBodyLengthFromHeader(ref ReadOnlySequence<byte> buffer)
        {
            var reader = new SequenceReader<byte>(buffer);
            reader.Advance(2); // skip the first byte
            reader.TryReadBigEndian(out short len);
            if (len <= 0)
                throw new ProtocolException("len<0");
            return len+1;
        }
        
        protected override MessagePackageInfo DecodePackage(ref ReadOnlySequence<byte> buffer)
        {

            try
            {
                var package = new MessagePackageInfo(); 
                var reader = new SequenceReader<byte>(buffer); 
                reader.TryRead(out byte firstKey);
                if (firstKey != 0x25)
                {
                    throw new ProtocolException("协议头错误");
                }
                reader.TryRead(out byte packageKey);
                package.Key = packageKey;
                 
                
                short total_len = 0;
                short topic_len = 0;
                short content_len = 0;
                reader.TryReadBigEndian(out   total_len); 
                reader.TryReadBigEndian(out   topic_len);

                //订阅
                if (packageKey == 0x04 && topic_len == 0)
                {
                    throw new ProtocolException("topic is null");
                }
                if (topic_len > 0)
                {
                    ReadOnlySequence<byte> buffer_topic=   reader.Sequence.Slice(reader.Consumed, topic_len);
                    package.Topic = Encoding.UTF8.GetString(buffer_topic);
                }
                reader.Advance(topic_len);
                reader.TryReadBigEndian(out   content_len);

                if (topic_len == 0 && content_len == 0)
                {
                    throw new ProtocolException("不能传输空");
                }
                if (content_len > 0)
                {
                    ReadOnlySequence<byte> buffer_content = reader.Sequence.Slice(reader.Consumed, content_len);
                    package.Body = buffer_content.ToArray();
                    reader.Advance(content_len); 
                }  
                byte endSignal;
                reader.TryRead(out endSignal);
                if (endSignal != 0x26)
                {
                
                    throw new ProtocolException("协议错误");
                
                }
                return package;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
          
            // package.Len = len; 
            // long length = reader.Remaining-1; 
            // if (len == 0)
            // {
            //     
            //     this.Reset();
            //     throw new ProtocolException("协议错误");
            // }
            // if (len != length)
            // {
            //     throw new ProtocolException("协议错误");
            // }
            //
            //  ReadOnlySequence<byte> buffer_body = reader.Sequence.Slice(reader.Consumed, length);
            //     
            //  package.Body = buffer_body.ToArray();
            //  reader.Advance(len);
            //  byte endSignal;
            //  reader.TryRead(out endSignal);
            //
            //  if (endSignal != 0x26)
            //  {
            //
            //      throw new ProtocolException("协议错误");
            //
            //  }
          

            
        }
    }
}